package com.fmdj.vhr.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import com.fmdj.common.util.CommonResult;
import com.fmdj.common.util.PageUtils;
import com.fmdj.vhr.controller.form.*;
import com.fmdj.vhr.db.pojo.VoucherEntity;
import com.fmdj.vhr.service.VoucherService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/voucher")
@Tag(name = "VoucherController", description = "代金卷Web接口")
@Slf4j
public class VoucherController {
    @Autowired
    private VoucherService voucherService;

    @PostMapping("/insertVoucher")
    @Operation(summary = "添加代金卷")
    public CommonResult insertVoucher(@RequestBody @Valid InsertVoucherForm form) {
        Map map = BeanUtil.beanToMap(form);
        VoucherEntity entity = BeanUtil.toBean(map, VoucherEntity.class);
        entity.setUuid(IdUtil.simpleUUID());
        int rows = voucherService.insert(entity);
        return CommonResult.ok().put(CommonResult.RETURN_ROW, rows);
    }

    @PostMapping("/searchVoucherByPage")
    @Operation(summary = "查询代金卷")
    public CommonResult searchVoucherByPage(@RequestBody @Valid SearchVoucherByPageForm form) {
        Map map = BeanUtil.beanToMap(form);
        Integer page = MapUtil.getInt(map, "page");
        Integer length = MapUtil.getInt(map, "length");
        int start = (page - 1) * length;
        map.put("start", start);
        PageUtils pageUtils = voucherService.searchVoucherByPage(map);
        return CommonResult.ok().put(CommonResult.RETURN_RESULT, pageUtils);
    }

    @PostMapping("/updateVoucherStatus")
    @Operation(summary = "更新代金卷的状态")
    public CommonResult updateVoucherStatus(@RequestBody @Valid UpdateVoucherStatusForm form) {
        Map map = BeanUtil.beanToMap(form);
        int rows = voucherService.updateVoucherStatus(map);
        return CommonResult.ok().put(CommonResult.RETURN_ROW, rows);
    }


    @PostMapping("/deleteVoucherByIds")
    @Operation(summary = "删除代金卷")
    public CommonResult deleteVoucherByIds(@RequestBody @Valid DeleteVoucherByIdsForm form) {
        int rows = voucherService.deleteVoucherByIds(form.getIds());
        return CommonResult.ok().put(CommonResult.RETURN_ROW, rows);
    }

}
